<!-- views/admin/components/LeaveApproval.vue -->
<template>
  <div class="leave-approval-container">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>未审批的请假记录</h2>
    </div>

    <!-- 请假记录表格 -->
    <div class="table-container">
      <table class="leave-table">
        <thead>
          <tr>
            <th>申请ID</th>
            <th>员工ID</th>
            <th>申请人</th>
            <th>请假类型</th>
            <th>开始时间</th>
            <th>结束时间</th>
            <th>请假天数</th>
            <th>事由</th>
            <th>申请时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="record in leaveRecords" :key="record.applyId">
            <td>{{ record.applyId }}</td>
            <td>{{ record.empId }}</td>
            <td>{{ getEmployeeName(record.empId) }}</td>
            <td>{{ getLeaveTypeName(record.leaveType) }}</td>
            <td>{{ formatDate(record.startTime) }}</td>
            <td>{{ formatDate(record.endTime) }}</td>
            <td>{{ record.leaveDays }}</td>
            <td>{{ record.reason }}</td>
            <td>{{ formatDate(record.applyTime) }}</td>
            <td>
              <button 
                class="approve-btn" 
                @click="handleApprove(record.applyId)"
              >
                审批
              </button>
            </td>
          </tr>
          <tr v-if="leaveRecords.length === 0 && !loading">
            <td colspan="10" class="empty-text">暂无未审批的请假记录</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 加载状态 -->
    <div class="loading" v-if="loading">加载中...</div>
  </div>
  <!-- 添加查询输入框 -->
<div class="search-container">
  <input 
    v-model="searchId" 
    type="number" 
    placeholder="请输入请假记录ID"
    @keyup.enter="searchLeaveRecord"
  >
  <button @click="searchLeaveRecord">查询</button>
</div>

<!-- 添加查询结果展示区域 -->
<div v-if="selectedRecord" class="record-detail">
  <h3>请假记录详情</h3>
  <div class="detail-item">
    <span>申请ID:</span>
    <span>{{ selectedRecord.applyId }}</span>
  </div>
  <div class="detail-item">
    <span>员工ID:</span>
    <span>{{ selectedRecord.empId }}</span>
  </div>
  <div class="detail-item">
    <span>申请人:</span>
    <span>{{ getEmployeeName(selectedRecord.empId) }}</span>
  </div>
  <div class="detail-item">
    <span>请假类型:</span>
    <span>{{ getLeaveTypeName(selectedRecord.leaveType) }}</span>
  </div>
  <div class="detail-item">
    <span>开始时间:</span>
    <span>{{ formatDate(selectedRecord.startTime) }}</span>
  </div>
  <div class="detail-item">
    <span>结束时间:</span>
    <span>{{ formatDate(selectedRecord.endTime) }}</span>
  </div>
  <div class="detail-item">
    <span>请假天数:</span>
    <span>{{ selectedRecord.leaveDays }}</span>
  </div>
  <div class="detail-item">
    <span>事由:</span>
    <span>{{ selectedRecord.reason }}</span>
  </div>
  <div class="detail-item">
    <span>申请时间:</span>
    <span>{{ formatDate(selectedRecord.applyTime) }}</span>
  </div>
  <div class="detail-item">
    <span>状态:</span>
    <span>{{ getStatusText(selectedRecord.status) }}</span>
  </div>
</div><!-- 添加无记录提示 -->
<div v-else-if="searchId && !selectedRecord" class="no-record">
  <p>未找到ID为 {{ searchId }} 的请假记录</p>
</div>
</template>

<script>
import { getUnapprovedLeaveRecords, updateLeaveStatus, getLeaveRecordById  } from '@/api/leaveManage'

export default {
  name: 'LeaveApproval',
  data() {
    return {
      leaveRecords: [], // 请假记录列表
      loading: false, // 加载状态
      searchId: '', // 查询ID
      selectedRecord: null, // 选中的记录
      employeeMap: { // 员工信息映射（实际项目中应从API获取）
        1: '张三',
        2: '李四',
        3: '王五'
      },
      leaveTypeMap: { // 请假类型映射
        1: '事假',
        2: '病假',
        3: '年假',
        4: '婚假',
        5: '产假'
      },
      statusMap: { // 状态映射
        0: '待审批',
        1: '已通过',
        2: '已拒绝'
      }
    }
  },
  created() {
    this.loadLeaveRecords()
  },
  methods: {
    /**
     * 根据ID查询请假记录
     */
    async searchLeaveRecord() {
      if (!this.searchId) {
        alert('请输入请假记录ID')
        return
      }
      
      try {
        const response = await getLeaveRecordById(this.searchId)
        this.selectedRecord = response.data || null
      } catch (error) {
        alert(error.message || '查询失败，请重试')
        this.selectedRecord = null
      }
    },

    /**
     * 获取状态文本
     * @param {number} status - 状态码
     * @returns {string} 状态文本
     */
    getStatusText(status) {
      return this.statusMap[status] || '未知状态'
    },

    /**
     * 加载未审批的请假记录
     */
    async loadLeaveRecords() {
      this.loading = true
      try {
        const response = await getUnapprovedLeaveRecords()
        this.leaveRecords = response.data || []
      } catch (error) {
        console.error('加载请假记录失败:', error)
        this.leaveRecords = []
      } finally {
        this.loading = false
      }
    },

    /**
     * 根据员工ID获取员工姓名
     * @param {number} empId - 员工ID
     * @returns {string} 员工姓名
     */
    getEmployeeName(empId) {
      return this.employeeMap[empId] || '未知员工'
    },

    /**
     * 根据请假类型ID获取类型名称
     * @param {number} leaveType - 请假类型ID
     * @returns {string} 请假类型名称
     */
    getLeaveTypeName(leaveType) {
      return this.leaveTypeMap[leaveType] || '未知类型'
    },

    /**
     * 格式化日期显示
     * @param {string} dateStr - 日期字符串
     * @returns {string} 格式化后的日期
     */
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return date.toLocaleString()
    },

    /**
     * 处理审批操作
     * @param {number} applyId - 申请ID
     */
    async handleApprove(applyId) {
      // 弹出审批对话框
      const status = prompt('请输入审批意见（1通过或2拒绝）：')
      if (!status) return
      
      const approveStatus = status.trim().toLowerCase() === '通过' ? 1 : 2
      const approvalOpinion = status
      
      // 获取当前登录用户ID（实际项目中应从用户信息中获取）
      const approverId = 1 // 示例值，实际项目中应替换为当前用户ID
      
      if (confirm(`确定要${status}该请假申请吗？（1通过或2拒绝）`)) {
        try {
          const response = await updateLeaveStatus({
            id: applyId,
            status: approveStatus,
            approverId: approverId,
            approvalOpinion: approvalOpinion
          })
          alert(response.message || '审批成功')
          this.loadLeaveRecords() // 重新加载列表
        } catch (error) {
          alert(error.message || '审批失败，请重试')
        }
      }
    }
  }
}
</script>

<style scoped>
.leave-approval-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  margin-bottom: 20px;
  text-align: center;
}

.leave-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.leave-table th,
.leave-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.leave-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.leave-table tr:hover {
  background-color: #f9f9f9;
}

.empty-text {
  text-align: center;
  padding: 30px;
  color: #999;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.approve-btn {
  padding: 6px 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.approve-btn:hover {
  background-color: #45a049;
}
</style>